//
//  BSDNetTool.m
//  BaishidaiShop
//
//  Created by mac book on 2019/1/18.
//  Copyright © 2019年 sy. All rights reserved.


#import "BSDNetTool.h"

@implementation BSDNetTool

static AFHTTPSessionManager *_manager;


+ (void)requestCancel{
    
    [_manager.operationQueue cancelAllOperations];
}

/** *  类方法 */
+ (BSDNetTool *)sharedUtil {
    static dispatch_once_t  onceToken;
    static BSDNetTool * setSharedInstance;
    dispatch_once(&onceToken, ^{
        
        setSharedInstance = [[BSDNetTool alloc] init];
        
    });
    return setSharedInstance;
}




+ (AFHTTPSessionManager *)sharedManager {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        
        _manager = [AFHTTPSessionManager manager];
        // 2.申明返回的结果是二进制类型
        _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        // 3.如果报接受类型不一致请替换一致text/html  或者 text/plain
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
        // 4.请求超时，时间设置
        _manager.requestSerializer.timeoutInterval = 30;
        
        [_manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        [_manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];



    });
    return _manager;
}


/** * AFN get数据请求 */
+(void)GetURL:(NSString *)URLString
    parameters:(NSDictionary*)parameters
       succeed:(void (^)(NSDictionary* data))succeed
       failure:(void (^)(NSError *error))failure{
    
    _manager = [self sharedManager];
    [_manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        succeed([BSDNetTool dictionaryWithJsonString:responseStr]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}


/** * AFN post数据请求 */
+(void)PostURL:(NSString *)URLString
    parameters:(NSDictionary *)parameters
       succeed:(void (^)(NSDictionary* data))succeed
       failure:(void (^)(NSError *error))failure{
    
    _manager = [self sharedManager];
    [_manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        succeed([BSDNetTool dictionaryWithJsonString:responseStr]);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
}
/** * 上传单张图片 */
+(void)requestAFURL:(NSString *)URLString
         parameters:(id)parameters
          imageData:(NSData *)imageData
            succeed:(void (^)(NSDictionary* data))succeed
            failure:(void (^)(NSError *error))failure{
    
    _manager = [self sharedManager];
    // 5. POST数据
    [_manager POST:URLString  parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmssSSS";
        // 设置时间格式
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        //将得到的二进制图片拼接到表单中 /** data,指定上传的二进制流;name,服务器端所需参数名*/
        [formData appendPartWithFileData:imageData name:@"img" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
    }progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *responseStr =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        succeed([BSDNetTool dictionaryWithJsonString:responseStr]);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
}
/** * 上传多张图片 */
+(void)requestAFURL:(NSString *)URLString
         parameters:(id)parameters
     imageDataArray:(NSArray *)imageDataArray
            succeed:(void (^)(NSDictionary* data))succeed
            failure:(void (^)(NSError *error))failure{
    
    _manager = [self sharedManager];
    [_manager POST:URLString
       parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
           for (int i = 0; i<imageDataArray.count; i++){
               UIImage *image = imageDataArray[i];
               NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
               
               
               // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
               // 要解决此问题，
               // 可以在上传时使用当前的系统事件作为文件名
               NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
               // 设置时间格式
               formatter.dateFormat = @"yyyyMMddHHmmss";
               NSString *str = [formatter stringFromDate:[NSDate date]];
               NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
               NSString *name = [NSString stringWithFormat:@"img%d",i ];
               //将得到的二进制图片拼接到表单中 /** data,指定上传的二进制流;name,服务器端所需参数名*/
               [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/jpg/png/jpeg"];
           }
       }progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
           NSString *responseStr =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
           succeed([BSDNetTool dictionaryWithJsonString:responseStr]);
       } failure:^(NSURLSessionDataTask *task, NSError *error) {
           failure(error);
       }];
}
/** * 上传文件 */
+(void)requestAFURL:(NSString *)URLString
         parameters:(id)parameters
           fileData:(NSData *)fileData
            succeed:(void (^)(id))succeed
            failure:(void (^)(NSError *error))failure{

    _manager = [self sharedManager];
    // 5. POST数据
    [_manager POST:URLString  parameters:parameters  constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //将得到的二进制数据拼接到表单中 /** data,指定上传的二进制流;name,服务器端所需参数名*/
        [formData appendPartWithFileData :fileData name:@"file" fileName:@"audio.MP3" mimeType:@"audio/MP3"];
    }progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *responseStr =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        succeed([BSDNetTool dictionaryWithJsonString:responseStr]);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
}





+(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData                                                        options:NSJSONReadingMutableContainers                                                          error:&error];
    if(error) {
        return nil;
    }
    return dic;
}


@end
